<div class="settings-container">
  <div class="flex align-items-center justify-content-between mb-4">
    <h1>Download Cleaner</h1>
  </div>

  <!-- Loading/Error State Component -->
  <app-loading-error-state
    *ngIf="downloadCleanerLoading() || downloadCleanerLoadError()"
    [loading]="downloadCleanerLoading()"
    [error]="downloadCleanerLoadError()"
    loadingMessage="Loading settings..."
    errorMessage="Could not connect to server"
  ></app-loading-error-state>

  <!-- Settings Form -->
  <form *ngIf="!downloadCleanerLoading() && !downloadCleanerLoadError()" [formGroup]="downloadCleanerForm" class="p-fluid">
    
    <p-card styleClass="settings-card h-full">
      <ng-template pTemplate="header">
        <div class="flex align-items-center justify-content-between p-3 border-bottom-1 surface-border">
          <div class="header-title-container">
            <h2 class="card-title m-0">Download Cleaner Configuration</h2>
            <span class="card-subtitle">Configure automatic download cleanup</span>
          </div>
        </div>
    </ng-template>

    <div class="card-content">
      <!-- Main Settings -->
      <div class="field-row">
        <label class="field-label">
          <i class="pi pi-question-circle field-info-icon"
             (click)="openFieldDocs('enabled')"
             title="Click for documentation"></i>
          Enable Download Cleaner
        </label>
        <div class="field-input">
          <p-checkbox formControlName="enabled" [binary]="true" inputId="dcEnabled"></p-checkbox>
          <small *ngIf="hasNoFeaturesConfiguredError()" class="form-error-text">At least one feature must be configured</small>
          <small class="form-helper-text">When enabled, the download cleaner will run according to the schedule</small>
        </div>
      </div>

      <!-- Scheduling Mode Toggle -->
      <div class="field-row">
        <label class="field-label">
          <i class="pi pi-question-circle field-info-icon" 
             (click)="openFieldDocs('useAdvancedScheduling')" 
             title="Click for documentation"></i>
          Scheduling Mode
        </label>
        <div class="field-input">
          <p-selectButton
            formControlName="useAdvancedScheduling"
            [options]="scheduleModeOptions"
            optionLabel="label"
            optionValue="value"
            [allowEmpty]="false"
            [multiple]="false"
          >
          </p-selectButton>
          <small class="form-helper-text">Choose between basic scheduling or advanced cron expression</small>
        </div>
      </div>

      <!-- Basic Schedule Controls - shown when useAdvancedScheduling is false -->
      <div class="field-row" formGroupName="jobSchedule" *ngIf="!downloadCleanerForm.get('useAdvancedScheduling')?.value">
        <label class="field-label">
          Run Schedule
        </label>
        <div class="field-input">
          <div class="schedule-input flex flex-wrap">
            <span class="schedule-label">Every</span>
            <p-select 
              formControlName="every"
              [options]="getScheduleValueOptions()"
              optionLabel="label"
              optionValue="value"
              placeholder="Select interval"
            ></p-select>

            <p-selectButton
              formControlName="type"
              [options]="scheduleUnitOptions"
              optionLabel="label"
              optionValue="value"
              [allowEmpty]="false"
              [multiple]="false"
            >
            </p-selectButton>
          </div>
          <small *ngIf="hasNestedError('jobSchedule', 'every', 'required')" class="form-error-text">This field is required</small>
          <small class="form-helper-text">How often the download cleaner should run</small>
        </div>
      </div>

      <!-- Advanced Schedule Controls - shown when useAdvancedScheduling is true -->
      <div class="field-row" *ngIf="downloadCleanerForm.get('useAdvancedScheduling')?.value">
        <label class="field-label">
          <i class="pi pi-question-circle field-info-icon" 
             (click)="openFieldDocs('cronExpression')" 
             title="Click for documentation"></i>
          Cron Expression
        </label>
        <div class="field-input">
          <input type="text" pInputText formControlName="cronExpression" placeholder="0 0/5 * ? * * *" />
          <small *ngIf="hasError('cronExpression', 'required')" class="form-error-text">Cron expression is required</small>
          <small class="form-helper-text">Enter a valid Quartz cron expression (e.g., "0 0/5 * ? * * *" runs every 5 minutes)</small>
        </div>
      </div>

      <!-- Ignored Downloads Field -->
      <div class="field-row">
        <label class="field-label">
          <i class="pi pi-question-circle field-info-icon"
             (click)="openFieldDocs('ignoredDownloads')"
             title="Click for documentation"></i>
          Ignored Downloads
        </label>
        <div class="field-input">
          <app-mobile-autocomplete
            formControlName="ignoredDownloads"
            placeholder="Add download pattern"
          ></app-mobile-autocomplete>
          <small class="form-helper-text">Downloads matching these patterns will be ignored by the download cleaner</small>
        </div>
      </div>

      <!-- Detailed Settings in Accordion -->
      <p-accordion [multiple]="false" [value]="activeAccordionIndices" styleClass="mt-3">
        <!-- Seeding Settings -->
        <p-accordion-panel [disabled]="!downloadCleanerForm.get('enabled')?.value" [value]="0">
          <p-accordion-header>
            <ng-template #toggleicon let-active="active">
              @if (active) {
                <i class="pi pi-chevron-up"></i>
              } @else {
                <i class="pi pi-chevron-down"></i>
              }
            </ng-template>
            <span class="accordion-header-title">
              Seeding Settings
              @if (sectionHasErrors(0)) {
                <i class="pi pi-exclamation-circle accordion-error-icon" title="This section has validation errors"></i>
              }
            </span>
          </p-accordion-header>
          <p-accordion-content>
            <!-- Delete Private Option -->
            <div class="field-row">
              <label class="field-label">
                <i class="pi pi-question-circle field-info-icon" 
                   (click)="openFieldDocs('deletePrivate')" 
                   title="Click for documentation"></i>
                Delete Private Torrents
              </label>
              <div class="field-input">
                <p-checkbox formControlName="deletePrivate" [binary]="true" inputId="deletePrivate"></p-checkbox>
                <small class="form-helper-text">When enabled, private torrents will be deleted</small>
              </div>
            </div>

            <!-- Categories Management -->
            <div class="section-header mt-4 mb-2">
              <h3>Seeding Rules</h3>
              <small>Configure categories for automatic cleanup</small>
            </div>

            <!-- Categories Vertical Layout -->
            <div class="categories-container mb-3">
              <!-- Empty state message when no categories -->
              <div *ngIf="categoriesFormArray.controls.length === 0" class="empty-categories-message p-3 text-center">
                <p>No categories defined. Add a category to start cleaning downloads.</p>
              </div>
              
              <!-- Category cards -->
              <div class="category-list">
                <div *ngFor="let category of categoriesFormArray.controls; let i = index" class="category-item" [formGroup]="getCategoryAsFormGroup(i)">
                  <div class="category-header">
                    <div class="category-title">
                      <i class="pi pi-question-circle field-info-icon" 
                         (click)="openFieldDocs('name')" 
                         title="Click for documentation"></i>
                      <input type="text" pInputText formControlName="name" placeholder="Category name" class="category-name-input" />
                    </div>
                    <button pButton type="button" icon="pi pi-trash" class="p-button-danger p-button-sm" 
                      (click)="removeCategory(i)" [disabled]="downloadCleanerForm.disabled"></button>
                  </div>
                  <small *ngIf="hasCategoryError(i, 'name', 'required')" class="form-error-text">Name is required</small>
                  
                  <div class="category-content">
                    <div class="category-field">
                      <label>
                        <i class="pi pi-question-circle field-info-icon" 
                           (click)="openFieldDocs('maxRatio')" 
                           title="Click for documentation"></i>
                        Max Ratio
                      </label>
                      <div class="field-input">
                        <p-inputNumber formControlName="maxRatio" [min]="-1" [showButtons]="true" buttonLayout="horizontal"
                          [minFractionDigits]="2" [maxFractionDigits]="2" [useGrouping]="false"
                          decrementButtonClass="p-button-danger" incrementButtonClass="p-button-success" incrementButtonIcon="pi pi-plus"
                          decrementButtonIcon="pi pi-minus">
                        </p-inputNumber>
                        <small *ngIf="hasCategoryError(i, 'maxRatio', 'required')" class="form-error-text">This input is required</small>
                        <small *ngIf="hasCategoryError(i, 'maxRatio', 'min')" class="form-error-text">Min value is -1</small>
                        <small class="form-helper-text">Maximum ratio to seed before removing (<code>-1</code> means disabled)</small>
                      </div>
                    </div>
                    
                    <div class="category-field">
                      <label>
                        <i class="pi pi-question-circle field-info-icon" 
                           (click)="openFieldDocs('minSeedTime')" 
                           title="Click for documentation"></i>
                        Min Seed Time (hours)
                      </label>
                      <div class="field-input">
                        <p-inputNumber formControlName="minSeedTime" [min]="0" [showButtons]="true" buttonLayout="horizontal"
                          decrementButtonClass="p-button-danger" incrementButtonClass="p-button-success" incrementButtonIcon="pi pi-plus"
                          decrementButtonIcon="pi pi-minus">
                        </p-inputNumber>
                        <small *ngIf="hasCategoryError(i, 'minSeedTime', 'required')" class="form-error-text">This input is required</small>
                        <small *ngIf="hasCategoryError(i, 'minSeedTime', 'min')" class="form-error-text">Min value is 0</small>
                        <small class="form-helper-text">Minimum time to seed before removing a download that has reached the max ratio (<code>0</code> means disabled)</small>
                      </div>
                    </div>
                    
                    <div class="category-field">
                      <label>
                        <i class="pi pi-question-circle field-info-icon" 
                           (click)="openFieldDocs('maxSeedTime')" 
                           title="Click for documentation"></i>
                        Max Seed Time (hours)
                      </label>
                      <div class="field-input">
                        <p-inputNumber formControlName="maxSeedTime" [min]="-1" [showButtons]="true" buttonLayout="horizontal"
                          decrementButtonClass="p-button-danger" incrementButtonClass="p-button-success" incrementButtonIcon="pi pi-plus"
                          decrementButtonIcon="pi pi-minus">
                        </p-inputNumber>
                        <small *ngIf="hasCategoryError(i, 'maxSeedTime', 'required')" class="form-error-text">This input is required</small>
                        <small *ngIf="hasCategoryError(i, 'maxSeedTime', 'min')" class="form-error-text">Min value is -1</small>
                        <small class="form-helper-text">Maximum time to seed before removing (<code>-1</code> means disabled)</small>
                      </div>
                    </div>
                  </div>
                  <!-- Error for both maxRatio and maxSeedTime disabled -->
                  <small *ngIf="hasCategoryGroupError(i, 'bothDisabled')" class="form-error-text">
                    Both max ratio and max seed time cannot be disabled at the same time
                  </small>
                </div>
              </div>
              
              <div class="flex justify-content-end mt-3">
                <button pButton type="button" icon="pi pi-plus" label="Add Category" 
                  (click)="addCategory()" [disabled]="downloadCleanerForm.get('enabled')?.value === false" class="p-button-outlined"></button>
              </div>
            </div>
          </p-accordion-content>
        </p-accordion-panel>

        <!-- Unlinked Download Settings -->
        <p-accordion-panel [disabled]="!downloadCleanerForm.get('enabled')?.value" [value]="1">
          <p-accordion-header>
            <ng-template #toggleicon let-active="active">
              @if (active) {
                <i class="pi pi-chevron-up"></i>
              } @else {
                <i class="pi pi-chevron-down"></i>
              }
            </ng-template>
            <span class="accordion-header-title">
              Unlinked Download Settings
              @if (sectionHasErrors(1)) {
                <i class="pi pi-exclamation-circle accordion-error-icon" title="This section has validation errors"></i>
              }
            </span>
          </p-accordion-header>
          <p-accordion-content>
            <div class="field-row">
              <label class="field-label">
                <i class="pi pi-question-circle field-info-icon" 
                   (click)="openFieldDocs('unlinkedEnabled')" 
                   title="Click for documentation"></i>
                Enable Unlinked Download Handling
              </label>
              <div class="field-input">
                <p-checkbox formControlName="unlinkedEnabled" [binary]="true" inputId="unlinkedEnabled"></p-checkbox>
                <small class="form-helper-text">Enable management of downloads that have no hardlinks</small>
              </div>
            </div>

            <!-- Unlinked Target Category -->
            <div class="field-row">
              <label class="field-label">
                <i class="pi pi-question-circle field-info-icon" 
                   (click)="openFieldDocs('unlinkedTargetCategory')" 
                   title="Click for documentation"></i>
                Target Category
              </label>
              <div class="field-input">
                <input type="text" pInputText formControlName="unlinkedTargetCategory" placeholder="Target category name" />
                <small *ngIf="hasError('unlinkedTargetCategory', 'required')" class="form-error-text">Target category is required</small>
                <small class="form-helper-text">Category to move unlinked downloads to</small>
                <small class="form-helper-text">You have to create a seeding rule for this category if you want to remove the downloads</small>
              </div>
            </div>

            <!-- Use Tag Option -->
            <div class="field-row">
              <label class="field-label">
                <i class="pi pi-question-circle field-info-icon" 
                   (click)="openFieldDocs('unlinkedUseTag')" 
                   title="Click for documentation"></i>
                Use Tag
              </label>
              <div class="field-input">
                <p-checkbox formControlName="unlinkedUseTag" [binary]="true" inputId="unlinkedUseTag"></p-checkbox>
                <small class="form-helper-text">When enabled, uses a tag instead of category (qBittorrent only)</small>
              </div>
            </div>

            <!-- Ignored Root Directory -->
            <div class="field-row">
              <label class="field-label">
                <i class="pi pi-question-circle field-info-icon" 
                   (click)="openFieldDocs('unlinkedIgnoredRootDir')" 
                   title="Click for documentation"></i>
                Ignored Root Directory
              </label>
              <div class="field-input">
                <input type="text" pInputText formControlName="unlinkedIgnoredRootDir" placeholder="/path/to/directory" />
                <small class="form-helper-text">Root directory to ignore when checking for unlinked downloads (used for cross-seed)</small>
              </div>
            </div>

            <!-- Unlinked Categories -->
            <div class="field-row">
              <label class="field-label">
                <i class="pi pi-question-circle field-info-icon"
                   (click)="openFieldDocs('unlinkedCategories')"
                   title="Click for documentation"></i>
                Unlinked Categories
              </label>
                <div class="field-input">
                  <app-mobile-autocomplete
                    formControlName="unlinkedCategories"
                    placeholder="Add category"
                  ></app-mobile-autocomplete>
                  <small *ngIf="hasUnlinkedCategoriesError()" class="form-error-text">At least one category is required when unlinked download handling is enabled</small>
                  <small class="form-helper-text">Categories to check for unlinked downloads</small>
                </div>
            </div>
          </p-accordion-content>
        </p-accordion-panel>
      </p-accordion>

      <!-- Form Actions -->
      <div class="card-footer mt-3">
        <button
          pButton
          type="button"
          label="Save"
          icon="pi pi-save"
          class="p-button-primary"
          [disabled]="!downloadCleanerForm.dirty || !downloadCleanerForm.valid || !hasActualChanges || downloadCleanerSaving()"
          [loading]="downloadCleanerSaving()"
          (click)="saveDownloadCleanerConfig()"
        ></button>
        <button
          pButton
          type="button"
          label="Reset"
          icon="pi pi-refresh"
          class="p-button-secondary p-button-outlined ml-2"
          (click)="resetDownloadCleanerConfig()"
        ></button>
      </div>
    </div>
  </p-card>
  </form>

  <!-- Confirmation Dialog -->
  <p-confirmDialog
    rejectButtonStyleClass="p-button-text">
  </p-confirmDialog>
</div>